const bcrypt = require('bcrypt');

const {
    User,
    validateUser
} = require('../../model/user');

module.exports = async (req, res, next) => {

    try {
        await validateUser(req.body);
    } catch (ex) {
        // 验证失败重定向到添加用户页面
        // return res.redirect(`/admin/user-edit?message=${ex.message}`);
        return next(JSON.stringify({
            path: '/admin/user-edit',
            message: ex.message
        }));
    }


    let user = await User.findOne({
        email: req.body.email
    });

    if (user) {
        return next(JSON.stringify({
            path: '/admin/user-edit',
            message: "邮箱地址已被占用"
        }));
    }

    // 生成秘钥
    const salt = await bcrypt.genSalt(10);
    // 加密密码并替换原始密码
    req.body.password = await bcrypt.hash(req.body.password, salt);
    await User.create(req.body);

    res.redirect('/admin/user');
}